package net;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * @author krystal
 * @date 2022/11/27 18:00
 */
public class UdpEchoClient {
    DatagramSocket socket=null;
    private String serverIp;
    private int serverPort;

    public UdpEchoClient(String serverIp,int serverPort) throws SocketException {
        socket=new DatagramSocket();
        this.serverIp=serverIp;
        this.serverPort=serverPort;
    }

    public void start() throws IOException {
        Scanner scanner=new Scanner(System.in);
        while (true){
            //1、从控制台读取用户输入的内容
            System.out.print("->");
            String request=scanner.next();
            //2、构造一个UDP请求，发送给服务器
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(this.serverIp),this.serverPort);
            socket.send(requestPacket);
            //3、从服务器上读取UDP数据，并解析
            DatagramPacket responsePacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response=new String(responsePacket.getData(),responsePacket.getData().length);
            //4、把服务器的响应显示到控制台上
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
